<script setup lang="ts">
import { watch, ref, markRaw, onMounted } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import * as echarts from "echarts";
import { cloneDeep } from "@pureadmin/utils";
import { nextTick } from "process";
import { deepCopy } from "@/views/all/visual/template/utils";
defineOptions({
  name: "VChartPie"
});
const echartRef = ref();
let echartInstance: echarts.ECharts;
const isCollapsed = ref(false);
const dataTmpl = {
  type: "gauge",
  center: ["25%", "27%"], // Position for the third gauge
  radius: "50%",
  startAngle: 180,
  endAngle: 0,
  min: 0,
  max: 100,
  splitNumber: 5,
  axisLine: {
    lineStyle: {
      width: 18,
      splitNumber: 5
    }
  },
  progress: {
    show: true,
    width: 18,
    itemStyle: {
      color: "#3B82F6"
    }
  },
  pointer: {
    length: "60%",
    width: 6,
    itemStyle: {
      color: "rgba(0,0,0,0,0.8)"
    }
  },
  axisTick: {
    length: 8,
    lineStyle: {
      color: "#e4ece3"
    }
  },
  splitLine: {
    length: 12,
    lineStyle: {
      color: "#e4ece3"
    }
  },
  axisLabel: {
    color: "#464646",
    distance: 10
  },
  title: {
    offsetCenter: [0, "60%"], // Adjusted for the third gauge name
    fontSize: 14,
    show: true,
    color: "#000"
  },
  detail: {
    valueAnimation: true,
    formatter: "{value} kW",
    color: "#000",
    fontSize: 18,
    offsetCenter: [0, "40%"] // Adjusted position of value
  },
  data: [
    {
      value: 1303.1,
      name: "MV30"
    }
  ]
};
const props = withDefaults(
  defineProps<{
    propValue?: {
      contentList: Array<any>;
      title?: string;
      innerLabel?: string;
      collapsed?: boolean;
      iconName?: string;
      option?: Record<string, any>;
    };
    element?: {
      style: {
        width?: number;
        height?: number;
        display?: string;
      };
    };
  }>(),
  {
    propValue: () => ({
      contentList: [],
      option: {},
      title: "",
      innerLabel: "",
      collapsed: false,
      iconName: "alert"
    }),
    element: () => ({ style: {} })
  }
);
onMounted(() => {
  echartInstance = markRaw(
    echarts.init(echartRef.value, undefined, {
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    })
  );
  renderChart(props.propValue.contentList as any);
});
function getChartCoordinates(index) {
  const baseX = 25;
  const baseY = 27;
  const increment = 50;
  const xPercent = baseX + (index % 2) * increment + "%";
  const yPercent = baseY + Math.floor(index / 2) * increment + "%";
  return [xPercent, yPercent];
}
function findMinMax(arr) {
  if (arr.length === 0) {
    return { min: null, max: null };
  }

  const min = Math.min(...arr);
  const max = Math.max(...arr);

  return { min, max: Math.ceil(max / 9.5) * 10 };
}
function extractValues(arr, key) {
  return arr.map(item => item[key]);
}
function renderChart(newVal = []) {
  try {
    let option = cloneDeep(props.propValue.option);

    if (newVal && Array.isArray(newVal)) {
      let values = extractValues(newVal || [], "value");
      // let { min, max } = findMinMax(values);

      for (let i in newVal) {
        let item = newVal[i];
        let newTmpl = deepCopy(dataTmpl);
        newTmpl.center = getChartCoordinates(i);
        // newTmpl.max = max;
        newTmpl.data[0] = { value: values[i], name: item.title, ext1: item.ext1 };
        newTmpl.detail.formatter = `${item.ext1} ${item.unit}`;
        option.series[i] = newTmpl;
      }

      // option.series[0].tooltip.formatter = function (params) {};
    }
    // 设置参数

    // 更新大小
    if (echartInstance && echartInstance.resize) {
      echartInstance.resize({
        width: props.element!.style!.width! - 47,
        height: props.element.style.height! - 63
      });

      // 配置参数
      nextTick(() => {
        echartInstance.setOption(option);
      });
    }
  } catch (e) {
    console.error(e);
  }
}

//用于编辑器参数改变时响应变化
// watch(
//   () => props.element,
//   newVal => {
//     console.log(newVal);
//     renderChart(props.propValue.contentList);
//   },
//   { deep: true, immediate: true }
// );
watch(
  () => props.propValue.contentList,
  newVal => {
    renderChart(newVal as any);
  }
);
// watch(
//   () => props.element.dataBinding,
//   newVal => {
//     const { val } = newVal;

//     renderChart(val?.value?.attrs || ([] as any));
//   }
// );
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" :has-collapsed="propValue.collapsed">
    <div ref="echartRef" />
  </leftCompWrapper>
</template>
